﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _2FA
{
    public static class Base32Encoding
    {
        public static readonly char[] Base32Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".ToCharArray();
        public static byte[] ToBytes(string input)
        {
            var bits = input.ToUpper().ToCharArray().Select(c => Convert.ToString(Array.IndexOf(Base32Chars, c), 2).PadLeft(5, '0')).Aggregate((a, b) => a + b);
            return Enumerable.Range(0, bits.Length / 8).Select(i => Convert.ToByte(bits.Substring(i * 8, 8), 2)).ToArray();
        }

        public static string ToString(byte[] input)
        {
            var bits = input.Select(b => Convert.ToString(b, 2).PadLeft(8, '0')).Aggregate((a, b) => a + b);
            return new string(Enumerable.Range(0, bits.Length / 5).Select(i => Base32Chars[Convert.ToByte(bits.Substring(i * 5, 5), 2)]).ToArray());
        }



    }
}
